/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.music2;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.music2.R;

public class RenameItemActivity extends Activity
{
	public final static int RENAME_PLAYLIST = 0;
	public final static int RENAME_ARTIST = 1;
	public final static int RENAME_ALBUM = 2;
	public final static int RENAME_TRACK = 3;
	public final static int RENAME_FOLDER = 4;
	
	private EditText mPlaylist;
    private TextView mPrompt;
    private Button mSaveButton;
    private long mRenameId;
    private String mOriginalName;
    private int mRenameType;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.create_playlist);
        getWindow().setLayout(WindowManager.LayoutParams.FILL_PARENT,
                                    WindowManager.LayoutParams.WRAP_CONTENT);

        mPrompt = (TextView)findViewById(R.id.prompt);
        mPlaylist = (EditText)findViewById(R.id.playlist);
        mSaveButton = (Button) findViewById(R.id.create);
        mSaveButton.setOnClickListener(mOpenClicked);

        ((Button)findViewById(R.id.cancel)).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });

        mRenameId = icicle != null ? icicle.getLong("rename")
                : getIntent().getLongExtra("rename", -1);
        mOriginalName = (String) (icicle != null ? icicle.getString("original")
                : getIntent().getCharSequenceExtra("original"));
        String defaultname = icicle != null ? icicle.getString("defaultname") : mOriginalName;
        
        mRenameType = icicle != null ? icicle.getInt("type")
                : getIntent().getIntExtra("type", -1);
        
        if (mRenameId < 0 || mOriginalName == null || defaultname == null) {
            Log.i("@@@@", "Rename failed: " + mRenameId + "/" + defaultname);
            finish();
            return;
        }
        
        String promptformat;
        if (mOriginalName.equals(defaultname)) {
            promptformat = getString(R.string.rename_playlist_same_prompt);
        } else {
            promptformat = getString(R.string.rename_playlist_diff_prompt);
        }
                
        String prompt = String.format(promptformat, mOriginalName, defaultname);
        mPrompt.setText(prompt);
        mPlaylist.setText(defaultname);
        mPlaylist.setSelection(defaultname.length());
        mSaveButton.setText(R.string.create_playlist_create_text);;
    }
             
    @Override
    public void onSaveInstanceState(Bundle outcicle) {
        outcicle.putString("defaultname", mPlaylist.getText().toString());
        outcicle.putLong("rename", mRenameId);
        outcicle.putInt("type", mRenameType);
        outcicle.putString("original", mOriginalName);
    }
    
    @Override
    public void onResume() {
        super.onResume();
    }
    
    
    /***
     * MediaProvider does not support creation of albums directly,
	 * so update the existing song and it will create the album for us
     * @param name
     */
    private boolean updateAlbumNameInDB(String name) {

    	ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Audio.Media.ALBUM, name);
        resolver.update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                values,
                MediaStore.Audio.Media._ID + "=?",
                new String[] { Long.valueOf(mRenameId).toString()});

    	return true;
    	
    }
    
    private long getArtistIdFromSongId(long songid) {		
    		int artistid = 0;
    		try {
    			String where = MediaStore.Audio.Media._ID + "=" + songid;
    	        Cursor c = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
    	                new String[] {MediaStore.Audio.Media.ARTIST_ID}, 
    	                where, null, null);
    	        if (c != null) {
    	            if (c.moveToFirst()) {
    	            	artistid = c.getInt(0);
    	            }
    	            c.close();
    	        }
    		} catch (Exception e) {			
    		}
            return artistid;    	
    }
    
    /***
     * Check if a track with this name by the artist already exists - if so then
     * dont allow the rename, return false. If there is no existing track by the 
     * artist with this name, then update the name for this track (give then audio_id)
     * 
     * @param name
     */
    private boolean updateTrackNameInDB(String name) {

    	//Retrieve the artist id for the current song id
    	long artistId = getArtistIdFromSongId(mRenameId);
    	
    	//Determine if there is a song by this artist with the new name
        final String[] ccols = new String[] { MediaStore.Audio.Media._ID };
        
        //Build the where clause
        StringBuilder where = new StringBuilder();
        where.append(MediaStore.Audio.Media.ARTIST_ID + "=" + artistId);
        where.append(" AND ");
        where.append(MediaStore.Audio.Media.TITLE + " LIKE ?");
            
        //Query the database
		Cursor c = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
				ccols, where.toString(), new String[]{name}, null);
		if(c != null) {
			if (c.moveToFirst()) {
				Toast.makeText(this, "Track already exists for this artist", Toast.LENGTH_SHORT).show();
				c.close();
				return false;
			}
		}
		
        //Allow the rename - set the track for the id
        ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Audio.Media.TITLE, name);
        resolver.update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                values,
                MediaStore.Audio.Media._ID + "=?",
                new String[] { Long.valueOf(mRenameId).toString()});
        
    	return true;
    }
    
    /***
	 * MediaProvider does not support creation of artists directly,
	 * so update the existing song and it will create the artist for us
     * @param name
     */
    private boolean updateArtistNameInDB(String name) {

    	ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Audio.Media.ARTIST, name);
        resolver.update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                values,
                MediaStore.Audio.Media._ID + "=?",
                new String[] { Long.valueOf(mRenameId).toString()});
    	
    	return true;
    }
    
    /***
     * Update the playlist name - just set the name for this playlist id 
     * to the newly entered name
     * 
     * Create playlist has its own activity
     * @param name
     */
    private boolean updatePlaylistNameInDB(String name) {
    	//need to know the playlist id (we have as mRenameId)
        ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Audio.Playlists.NAME, name);
        resolver.update(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
                values,
                MediaStore.Audio.Playlists._ID + "=?",
                new String[] { Long.valueOf(mRenameId).toString()});
        return true;
    }
    
    /***
     * Update the playlist name - just set the name for this playlist id 
     * to the newly entered name
     * 
     * Create playlist has its own activity
     * @param name
     */
    private boolean updateFolderNameInDB(String name) {
    	//need to know the folder id (we have as mRenameId)
        ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues(1);
        values.put(ExtendedAudioProvider.FOLDER_NAME, name);
        resolver.update(ExtendedAudioProvider.CONTENT_URI_FOLDERS,
                values,
                ExtendedAudioProvider._ID + "=?",
                new String[] { Long.valueOf(mRenameId).toString()});
        return true;
    }

    private View.OnClickListener mOpenClicked = new View.OnClickListener() {
        public void onClick(View v) {
            String name = mPlaylist.getText().toString();
            if (name != null && name.length() > 0) {
            	String message = "";
            	boolean result = false;
            	switch(mRenameType) {
            	case RENAME_PLAYLIST:
            		result = updatePlaylistNameInDB(name);
            		message = getResources().getString(R.string.playlist_renamed_message);
            		break;
            	case RENAME_FOLDER:
            		result = updateFolderNameInDB(name);
            		message = getResources().getString(R.string.playlist_folder_renamed_message);
            		break;
            	case RENAME_ARTIST:
            		result = updateArtistNameInDB(name);
            		message = getResources().getString(R.string.artist_renamed_message);
            		break;
            	case RENAME_ALBUM:
            		result = updateAlbumNameInDB(name);
            		message = getResources().getString(R.string.album_renamed_message);
            		break;
            	case RENAME_TRACK:
            		result = updateTrackNameInDB(name);
            		message = getResources().getString(R.string.track_renamed_message);
            		break;
            	}
            	//If renamed ok
            	if(result) {       	                
	                setResult(RESULT_OK);
	                Toast.makeText(RenameItemActivity.this, message, Toast.LENGTH_SHORT).show();
	                finish();
            	}
            }
        }
    };
}
